<template>
    <view class="page">
        <view class="table-nav">
            注册账号
        </view>
        <view class="ID-box">
            身份选择
            <view class="ID-box-flex flex">
                <view :class="['ID-item', { active: item.checked }]" v-for="(item, index) in list" :key="item.id"
                    @click="handleID(index)">{{ item.identity }}</view>
            </view>
        </view>
        <form @submit="handleRegister">
            <view class="box flex">
                头像
                <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                    <image class="avatar" :src="form.avatar_url" mode="scaleToFill" />
                </button>
            </view>
            <view class="box flex">
                姓名
                <input type="nickname" class="weui-input" placeholder="请输入昵称" @nicknamereview="namereview"
                    :value="nickName" name="nickName" />
            </view>
            <view class="box flex">
                所在公司
                <input placeholder="请输入公司名称" v-model="form.company_name" />
            </view>
            <view class="box flex" @click="tapArea">
                所在城市
                <input placeholder="请选择 >" v-model="region" />
            </view>
            <button class="btn" form-type="submit">{{ type ? '立即修改' : '立即注册' }}</button>
        </form>
        <lotus-address v-on:choseVal="choseValue" :lotusAddressData="lotusAddressData"
            v-if="lotusAddressData.visible"></lotus-address>
        <u-popup :show="show" @close="close" @open="center" mode="center" :round="10">
            <view class="pop-box flex">
                <image :src="imgApi + 'images/wallet/icon-21.svg'" mode="scaleToFill" />
                <view class="pop-tip">恭喜您注册成功</view>
                <view class="pop-tip" style="margin-top: 24rpx;color: #FFB850;">赠送您{{ user_point.points_balance || '0'
                    }}积分</view>
                <view class="pop-tip-1" @click="handleNav('/pages/mine/mine')">可前往 <span>“我的”</span>页面查看</view>
                <view class="pop-btn" @click="handleNav('/pagesB/customerService/index?status=' + 'kefu')">确定</view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import lotusAddress from "../components/Winglau14-lotusAddress/Winglau14-lotusAddress.vue";
import { setUserInformation, userIdentity } from "@/utils/request.js";
export default {
    components: {
        lotusAddress,
    },
    data() {
        return {
            type: '',
            imgApi: this.$config.imgApi,
            show: false,
            lotusAddressData: {
                visible: false,
                distinguish: true,
                provinceName: "",
                cityName: "",
                show: true,
            },
            nickName: '',
            region: '',
            list: [],
            pass: false, // 用户名合法性
            form: {
                avatar_url: '',
                username: "",
                user_identity_id: []
            },
            user_point: {},
            userInfo: {}
        }
    },
    onLoad(option) {
        if (option.type) {
            this.type = option.type
        }
        this.getUser()
        if (uni.getStorageSync('userInfo')) {
            this.userInfo = JSON.parse(uni.getStorageSync('userInfo'))
            this.form.username = this.userInfo.username
            this.nickName = this.userInfo.username
            this.form.avatar_url = this.$config.showImgApi + this.userInfo.avatar_url
            this.form.company_name = this.userInfo.user_info.company_name || ""
            this.lotusAddressData = {
                visible: false,
                distinguish: true,
                provinceName: this.userInfo.province,
                cityName: this.userInfo.city,
                show: true,
            }
            this.pass = true
            this.region = `${this.userInfo.province || ""}${this.userInfo.city || ''}`
        }
    },
    methods: {
        handleNav(url) {
            uni.reLaunch({ url: url })
        },
        async setUserInformation(data) {
            return await setUserInformation(data)
        },
        handleRegister(e) {
            if (!this.list || !this.list.length) {
                uni.showToast({
                    title: '请等待数据加载',
                    icon: 'none',
                    mask: true
                });
                return;
            }

            this.form.username = e.detail.value.nickName;
            this.form.user_identity_id = this.list
                ? this.list
                    .filter(item => item && item.checked)
                    .map(item => item.id)
                : [];

            if (this.form.user_identity_id.length == 0) {
                uni.showToast({
                    title: '请选择身份',
                    icon: 'none',
                    mask: true
                });
                return;
            }
            if (this.$data.pass && this.form.avatar_url) {
                const avatarUrl = this.form.avatar_url.replace(this.$config.showImgApi, '');
                
                if (!avatarUrl || !this.form.company_name || !this.lotusAddressData.provinceName || !this.lotusAddressData.cityName || !this.form.username) {
                    uni.showToast({
                        title: '请填写完整信息',
                        icon: 'none',
                        mask: true
                    });
                    return;
                }
                
                const form = { 
                    ...this.form,
                    avatar_url: avatarUrl,
                    province: this.lotusAddressData.provinceName, 
                    city: this.lotusAddressData.cityName, 
                    token: uni.getStorageSync('token') 
                };
                
                console.log(form, 'form');
                uni.showLoading({
                    title: '加载中...',
                    mask: true
                });
                
                this.setUserInformation(form).then(result => {
                    console.log(result, 'result');
                    if (result) {
                        uni.hideLoading();
                        uni.setStorageSync('token', result.token);
                        uni.setStorageSync("userInfo", JSON.stringify(result));
                        this.user_point = result.user_point;
                        if (!this.type) {
                            this.show = true;
                        } else {
                            uni.navigateBack({ delta: 1 })
                        }
                    }
                }).catch(error => {
                    console.error(error);
                });
            }
        },
        tapArea() {
            this.lotusAddressData.visible = true;
        },
        choseValue(res) {
            //res数据源包括已选省市区与省市区code
            console.log(res);
            this.lotusAddressData.visible = res.visible; //visible为显示与关闭组件标识true显示false隐藏
            //res.isChose = 1省市区已选 res.isChose = 0;未选
            if (res.isChose) {
                this.lotusAddressData.provinceName = res.province; //省
                this.lotusAddressData.cityName = res.city; //市
                // this.lotusAddressData.townName = res.town; //区
                this.region = `${res.province}${res.city}`; //region为已选的省市区的值
            }
        },
        handleID(index) {
            this.list[index].checked = !this.list[index].checked
        },
        onChooseAvatar(e) {
            console.log(e)
            let that=this
            this.$data.form.avatar_url = e.detail.avatarUrl
            uni.uploadFile({
                url: that.$config.upLoadApi + 'file/imageUpload', // 接口地址
                filePath: that.form.avatar_url,
                name: 'file',
                formData: {
                    file: that.form.avatar_url,
                    token: uni.getStorageSync('token'),
                },
                success: (res) => {
                    console.log(res, 'res');
                    var data = JSON.parse(res.data);
                    if (data.code == 200) {
                        that.form.avatar_url =this.$config.showImgApi +  data.path;
                    } else {
                        uni.showToast({
                            title: '上传失败',
                            duration: 2000,
                            icon: 'none'
                        });
                    }
                },
                fail: (err) => {
                    console.log(err, 'err');
                }
            });
        },
        async userIdentity() {
            return await userIdentity();
        },
        namereview: function (e) {
            this.$data.pass = e.detail.pass;
        },
        getUser() {
            this.userIdentity().then(res => {
                if (res && Array.isArray(res)) {
                    let list = res.map(element => {
                        return {
                            ...element,
                            checked: this.userInfo
                                ? this.userInfo.user_identity_id
                                    ? this.userInfo.user_identity_id[element.id] === element.identity
                                    : false
                                : false
                        };
                    });
                    this.list = list;
                } else {
                    console.error('Invalid response from userIdentity');
                    this.list = [];
                }
            }).catch(err => {
                console.error('Failed to get user identity:', err);
                this.list = [];
            });
        },
    }
}
</script>
<style lang="scss" scoped>
.page {
    width: 100%;
    height: 100vh;
    background-image: linear-gradient(to bottom, #ffb850, #f2f2f2, #ffffff);

    .pop-box {
        padding: 30rpx 28rpx 20rpx;
        background: #ffffff;
        border-radius: 20rpx;
        flex-direction: column;
        justify-content: center;
        border-radius: 20rpx;

        image {
            width: 124rpx;
            height: 107rpx;
        }

        .pop-tip {
            font-size: 24rpx;
            margin-top: 40rpx;
        }

        .pop-tip-1 {
            font-size: 21rpx;
            margin-top: 29rpx;

            span {
                color: #FFB850;
            }
        }

        .pop-btn {
            width: 432rpx;
            height: 84rpx;
            border-radius: 162rpx;
            background: #FFB850;
            margin: 17rpx auto 0;
            font-size: 25rpx;
            color: #ffffff;
            line-height: 84rpx;
            text-align: center;
        }
    }

    .box {
        width: 664rpx;
        margin: 0 auto;
        padding: 40rpx 0;
        border-bottom: 1rpx solid #7F7F7F;
        justify-content: space-between;

        input {
            font-size: 28rpx;
            text-align: right;
        }
    }

    .table-nav {
        margin-left: 43rpx;
        font-size: 44rpx;
        font-weight: bold;
        padding-top: 135rpx;
    }

    .avatar-wrapper {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin: 0;
        background: #F2F2F2;
        overflow: hidden;
        border: none;
        padding: 0;

        image {
            width: 100%;
            height: 100%;
        }
    }

    .ID-box {
        width: 664rpx;
        margin: 96rpx auto 30rpx;

        .ID-box-flex {
            margin-top: 40rpx;
            flex-wrap: wrap;

            .ID-item {
                padding: 10rpx 28rpx;
                border-radius: 132rpx;
                font-size: 23rpx;
                color: #333333;
                background: #F2F2F2;
                margin-right: 20rpx;
                margin-bottom: 22rpx;
            }

            .active {
                background: #FFB850;
                color: #ffffff;
            }
        }
    }
}
</style>